package com.lagou.edu.controller;

import com.alibaba.fastjson.JSONObject;
import com.lagou.edu.client.CodeFeignClient;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.IUserSerivce;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import java.util.UUID;

/**
 * @author 陶肖寅
 * @version V1.0
 * <p>
 *     用户接口控制层
 * @date 2020-05-06 11:29
 * @email fromlx@126.com
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 * </p>
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    CodeFeignClient codeFeignClient;
    @Autowired
    IUserSerivce userSerivce;
    /**
     * 注册接口
     * @param email 邮箱
     * @param password 密码
     * @param code 验证码
     * @return true/false true成功，false失败
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public String register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code")  String code,
                            HttpServletResponse response) {
        JSONObject result = new JSONObject();
       try {
            //step-1 判断邮件是否已注册
           User user = userSerivce.getUserByEmail(email);
           if (user !=null ) {
               result.put("code",Boolean.FALSE);
               result.put("msg","该邮箱已注册");
               return result.toJSONString();
           }
           //step-2 判断验证码是否正确
           Integer validate = codeFeignClient.validate(email, code);
           if (validate != 0) {
               result.put("code",Boolean.FALSE);
               result.put("msg","验证码出错");
               return result.toJSONString();
           }
           //step-2 生成token口令(uuid)
           String token = UUID.randomUUID().toString();
           //step-3 保存token令牌到redis中
           userSerivce.saveToken(email,token);
           //step-4 将数据保存到cookies
           Cookie cookie =new Cookie("token",token);
           cookie.setHttpOnly(true);
           response.addCookie(cookie);
           result.put("code",Boolean.TRUE);
           return result.toJSONString();
       } catch (Exception e) {
           e.printStackTrace();
           result.put("code",Boolean.FALSE);
           result.put("msg",e.getMessage());
           return result.toJSONString();
       }
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过， false代表尚未注册
     * @param email 邮箱
     * @return true/false true代表已经注册过， false代表尚未注册
     */
    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email){
        Token token = userSerivce.isRegistered(email);
        if (token != null) {
            return Boolean.TRUE;
        }
        return  Boolean.FALSE;

    }

    /**
     * 登录接口
     * @param email 邮箱
     * @param password 密码
     * @return 邮箱地址
     */
    @GetMapping("/login/{email}/{password}")
    public  String login(@PathVariable("email") String email,
                          @PathVariable("password") String password,
                         HttpServletResponse response){
            JSONObject result = new JSONObject();

        User user = userSerivce.getUserByEmail(email);
        if (user !=null && password.equals(user.getPassword())) {
            //step-2 生成token口令(uuid)
            String token = UUID.randomUUID().toString();
            //step-3 保存token令牌到redis中
            userSerivce.saveToken(email,token);
            //step-4 将数据保存到cookies
            Cookie cookie =new Cookie("token",token);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            result.put("code",Boolean.TRUE);
            result.put("email",email);
            return result.toJSONString();
        } else {
            result.put("code",Boolean.FALSE);
            result.put("msg","该邮件未注册");
            return result.toJSONString();
        }
    }

    /**
     * 根据token查询用户登录邮箱接口
     * @param  token token值
     * @return 邮箱地址
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable("token")  String token){
        Token tokenEntity = userSerivce.findTokenByToken(token);
        if (tokenEntity!=null) {
            return tokenEntity.getEmail();
        }
        return "";
    }
}
